import axios from 'axios';
import { wsService } from './websocket.service';

/**
 * AI图像生成服务
 * 提供文生图、图生图、图像编辑等功能
 */
class AIGenerationService {
    constructor() {
        this.apiUrl = import.meta.env.VITE_API_URL || '';
        this.isGenerating = false;
        this.currentPromptId = null;
        this.callbacks = {
            onStart: null,
            onProgress: null,
            onComplete: null,
            onError: null
        };

        // 初始化WebSocket连接
        this._setupWebSocket();
    }

    /**
     * 设置WebSocket事件监听
     * @private
     */
    _setupWebSocket() {
        // 确保WebSocket连接
        if (!wsService.isConnected()) {
            wsService.connect();
        }

        // 监听生成进度
        wsService.on('generation_progress', (data) => {
            if (this.callbacks.onProgress && this.currentPromptId === data.prompt_id) {
                this.callbacks.onProgress(data);
            }
        });

        // 监听生成完成
        wsService.on('generation_complete', (data) => {
            if (this.currentPromptId === data.prompt_id) {
                this.isGenerating = false;
                this.currentPromptId = null;

                if (this.callbacks.onComplete) {
                    this.callbacks.onComplete(data);
                }
            }
        });

        // 监听生成错误
        wsService.on('generation_error', (data) => {
            if (this.currentPromptId === data.prompt_id) {
                this.isGenerating = false;
                this.currentPromptId = null;

                if (this.callbacks.onError) {
                    this.callbacks.onError(data.error || '生成失败');
                }
            }
        });
    }

    /**
     * 设置回调函数
     * @param {Object} callbacks - 回调函数对象
     */
    setCallbacks(callbacks = {}) {
        this.callbacks = { ...this.callbacks, ...callbacks };
        return this;
    }

    /**
     * 文本到图像生成
     * @param {Object} params - 生成参数
     * @returns {Promise<Object>} 请求结果
     */
    async generateText2Image(params) {
        if (this.isGenerating) {
            throw new Error('已有生成任务正在进行中');
        }

        try {
            this.isGenerating = true;

            // 调用开始回调
            if (this.callbacks.onStart) {
                this.callbacks.onStart();
            }

            // 发送请求
            const response = await axios.post(`${this.apiUrl}/api/generation/text2img`, params);

            if (response.data && response.data.prompt_id) {
                // 保存当前任务ID
                this.currentPromptId = response.data.prompt_id;

                // 通过WebSocket订阅任务进度
                wsService.subscribeToTask(response.data.prompt_id);

                return response.data;
            } else {
                throw new Error('无效的响应数据');
            }
        } catch (error) {
            this.isGenerating = false;

            if (this.callbacks.onError) {
                this.callbacks.onError(error.message || '请求失败');
            }

            throw error;
        }
    }

    /**
     * 图像到图像生成
     * @param {File|Blob} imageFile - 源图像文件
     * @param {Object} params - 生成参数
     * @returns {Promise<Object>} 请求结果
     */
    async generateImg2Img(imageFile, params) {
        if (this.isGenerating) {
            throw new Error('已有生成任务正在进行中');
        }

        try {
            this.isGenerating = true;

            // 调用开始回调
            if (this.callbacks.onStart) {
                this.callbacks.onStart();
            }

            // 创建FormData
            const formData = new FormData();
            formData.append('image', imageFile);

            // 添加其他参数
            formData.append('params', JSON.stringify(params));

            // 发送请求
            const response = await axios.post(
                `${this.apiUrl}/api/generation/img2img`,
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
            );

            if (response.data && response.data.prompt_id) {
                // 保存当前任务ID
                this.currentPromptId = response.data.prompt_id;

                // 通过WebSocket订阅任务进度
                wsService.subscribeToTask(response.data.prompt_id);

                return response.data;
            } else {
                throw new Error('无效的响应数据');
            }
        } catch (error) {
            this.isGenerating = false;

            if (this.callbacks.onError) {
                this.callbacks.onError(error.message || '请求失败');
            }

            throw error;
        }
    }

    /**
     * 图像修复/擦除
     * @param {File|Blob} imageFile - 源图像文件
     * @param {File|Blob} maskFile - 遮罩图像文件
     * @param {Object} params - 生成参数
     * @returns {Promise<Object>} 请求结果
     */
    async generateInpainting(imageFile, maskFile, params) {
        if (this.isGenerating) {
            throw new Error('已有生成任务正在进行中');
        }

        try {
            this.isGenerating = true;

            // 调用开始回调
            if (this.callbacks.onStart) {
                this.callbacks.onStart();
            }

            // 创建FormData
            const formData = new FormData();
            formData.append('image', imageFile);
            formData.append('mask', maskFile);

            // 添加其他参数
            formData.append('params', JSON.stringify(params));

            // 发送请求
            const response = await axios.post(
                `${this.apiUrl}/api/generation/inpainting`,
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
            );

            if (response.data && response.data.prompt_id) {
                // 保存当前任务ID
                this.currentPromptId = response.data.prompt_id;

                // 通过WebSocket订阅任务进度
                wsService.subscribeToTask(response.data.prompt_id);

                return response.data;
            } else {
                throw new Error('无效的响应数据');
            }
        } catch (error) {
            this.isGenerating = false;

            if (this.callbacks.onError) {
                this.callbacks.onError(error.message || '请求失败');
            }

            throw error;
        }
    }

    /**
     * 取消当前生成任务
     * @returns {Promise<boolean>} 是否成功取消
     */
    async cancelGeneration() {
        if (!this.isGenerating || !this.currentPromptId) {
            return false;
        }

        try {
            const response = await axios.post(`${this.apiUrl}/api/generation/cancel`, {
                prompt_id: this.currentPromptId
            });

            this.isGenerating = false;
            this.currentPromptId = null;

            return true;
        } catch (error) {
            console.error('取消生成失败:', error);
            return false;
        }
    }

    /**
     * 获取模板列表
     * @param {string} category - 模板类别
     * @returns {Promise<Array>} 模板列表
     */
    async getTemplates(category = null) {
        try {
            const url = category
                ? `${this.apiUrl}/api/templates?category=${category}`
                : `${this.apiUrl}/api/templates`;

            const response = await axios.get(url);
            return response.data;
        } catch (error) {
            console.error('获取模板失败:', error);
            throw error;
        }
    }

    /**
     * 获取模板详情
     * @param {string} templateId - 模板ID
     * @returns {Promise<Object>} 模板详情
     */
    async getTemplateDetails(templateId) {
        try {
            const response = await axios.get(`${this.apiUrl}/api/templates/${templateId}`);
            return response.data;
        } catch (error) {
            console.error('获取模板详情失败:', error);
            throw error;
        }
    }

    /**
     * 获取用户预设列表
     * @returns {Promise<Array>} 预设列表
     */
    async getUserPresets() {
        try {
            const response = await axios.get(`${this.apiUrl}/api/presets`);
            return response.data;
        } catch (error) {
            console.error('获取预设失败:', error);
            throw error;
        }
    }

    /**
     * 保存用户预设
     * @param {Object} preset - 预设数据
     * @returns {Promise<Object>} 保存结果
     */
    async saveUserPreset(preset) {
        try {
            const response = await axios.post(`${this.apiUrl}/api/presets`, preset);
            return response.data;
        } catch (error) {
            console.error('保存预设失败:', error);
            throw error;
        }
    }
}

// 创建单例实例
export const aiService = new AIGenerationService();

// 默认导出服务实例
export default aiService; 